<template>
  <FModal ref="refFModal" @ok="ok" :header="modalTitle" width="1000">
    <el-form v-loading="loading"
             ref="refForm" label-width="100px" :model="userData">
      <div class="user-edit-body">
        <div class="user-edit-left">
          <el-text truncated tag="b">
            系统信息
          </el-text>
          <el-form-item prop="realname" label="姓名" :rules="[required]">
            <el-input placeholder="请输入姓名" v-model="userData.realname"/>
          </el-form-item>

          <el-form-item prop="username" label="登录名" :rules="[required]">
            <el-input autocomplete="new-password" placeholder="请输入登录名" v-model="userData.username"/>
          </el-form-item>

          <el-form-item prop="password" label="登录密码" :rules="[required]">
            <el-input autocomplete="new-password" type="password" placeholder="请输入登录密码"
                      v-model="userData.password"/>
          </el-form-item>

          <el-form-item prop="password1" label="密码确认" :rules="[required, password1Check]">
            <el-input type="password" placeholder="请输入密码" v-model="userData.password1"/>
          </el-form-item>

          <el-form-item prop="userStatus" label="账户状态" :rules="[required]">
            <SystemDict v-model="userData.userStatus" dict-code="userStatus" style="width: 100%"/>
          </el-form-item>

          <el-text truncated tag="b">
            个人信息
          </el-text>

          <el-form-item prop="sex" label="性别" :rules="[]">
            <SystemDict placeholder="请选择性别" v-model="userData.sex"
                        dict-code="sex" style="width: 100%"/>
          </el-form-item>

          <el-form-item prop="birthday" label="出生日期" :rules="[]">
            <el-date-picker placeholder="请选择出生日期" v-model="userData.birthday" style="width: 100%"/>
          </el-form-item>

          <el-form-item prop="tel" label="办公电话" :rules="[]">
            <el-input placeholder="请输入办公电话" v-model="userData.tel" style="width: 100%"/>
          </el-form-item>

          <el-form-item prop="mobile" label="手机号码" :rules="[]">
            <el-input placeholder="请输入手机号码" v-model="userData.mobile" style="width: 100%"/>
          </el-form-item>

          <el-form-item prop="email" label="邮件" :rules="[]">
            <el-input placeholder="请输入邮件" v-model="userData.email" style="width: 100%"/>
          </el-form-item>

          <el-form-item prop="userDesc" label="备注" :rules="[]">
            <el-input placeholder="请输入备注" type="textarea"
                      v-model="userData.userDesc" style="width: 100%"/>
          </el-form-item>
        </div>
        <div class="user-edit-right">
          <el-text truncated tag="b">
            组织信息
          </el-text>

          <el-form-item prop="userPositionDepartId" label="所属部门" :rules="[required]">
            <el-tree-select style="width: 100%" :props="defaultProps"
                            v-model="userData.userPositionDepartId"
                            :data="departTrees" default-expand-all
                            check-strictly node-key="id"
                            :render-after-expand="false"
            />
          </el-form-item>

          <el-form-item prop="userPositionSort" label="人员排序号" :rules="[required]">
            <el-input-number v-model="userData.userPositionSort"
                             placeholder="请输入排序号" style="width: 100%"/>
          </el-form-item>

          <el-form-item prop="userPosition" label="主岗" :rules="[required]">
            <el-select v-model="userData.userPosition"
                       style="width: 100%" clearable filterable>
              <el-option v-for="opt in positionOptions" :key="opt.id"
                         :label="opt.positionName" :value="opt.id"/>
            </el-select>
          </el-form-item>

          <el-form-item prop="userPosition" label="副岗" :rules="[]">
            <VicePositionModal v-model="userData.vicePositions" :unitData="unitData"
                               placeholder="请选择副岗"/>
          </el-form-item>

          <el-form-item prop="positionLevel" label="职务级别" :rules="[required]">
            <el-select v-model="userData.positionLevel" clearable style="width: 100%" filterable>
              <el-option v-for="opt in positionLevelOptions" :key="opt.id"
                         :label="opt.positionLevelName" :value="opt.id"/>
            </el-select>
          </el-form-item>

          <el-form-item prop="positionLevel" label="人员角色" :rules="[]">
            <UserRoleListModal v-model="userData.userRoles"
                               :unitData="unitData"/>
          </el-form-item>

          <el-form-item prop="avatar" label="人员照片" :rules="[]">
            <UserAvatar :circle="false" v-model="userData.avatar" :editable="true"/>
          </el-form-item>
        </div>
      </div>
    </el-form>
  </FModal>
</template>
<script setup>
import {computed, reactive, ref, shallowRef} from 'vue';
import FModal from '@/components/FModal/index.vue';
import {isEmpty, isNotEmpty, listToTrees, real, required} from '@/utils/CommonUtils';
import SystemDict from '@/components/SystemDict/index.vue';
import {getAction, postAction} from '@/request/BaseRequest';
import UserAvatar from '@/components/base/UserAvatar/index.vue';
import VicePositionModal from '@/views/system/UnitManagement/VicePositionModal/index.vue';
import {ElMessage} from 'element-plus';
import UserRoleListModal from '@/views/system/UnitManagement/UserRoleListModal/index.vue';

const refFModal = shallowRef();
const loading = shallowRef(false);
const refForm = shallowRef();
let unitData = undefined;
let departData = undefined;
const userData = ref({
  vicePositions: []
});
const defaultProps = {
  children: 'children',
  label: 'unitName',
};
const emits = defineEmits(['saved']);
const departTrees = shallowRef([]);
const positionOptions = shallowRef([]);
const positionLevelOptions = shallowRef([]);
const password1Check = reactive({
  trigger: ['blur', 'change'],
  validator(rule, value, callback) {
    if (value !== real(userData).password) {
      callback(new Error('两次输入的密码不一致'));
    }
    callback();
  },
});

function setData(_unitData, _departData, _userData) {
  unitData = _unitData;
  departData = _departData;
  userData.value = createDefaultValue();
  if (isEmpty(_userData)) {
    loadUserPositionSort();
    loadDefaultUserRoles();
  } else {
    loadUserData(_userData);
  }
  refFModal.value.open();
  loadUnitsByPath();
  loadUnitPositions();
  loadUnitPositionLevel();
}

function loadDefaultUserRoles() {
  loading.value = true;
  getAction("/sys/role/loadDefaultUserRolesByUnitId",
    {id: real(unitData).id}).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      setDefaultRoles(result);
    }
  });
}

function setDefaultRoles(roles) {
  if (isEmpty(roles)) return;
  let list = [];
  for (let i = 0; i < roles.length; i++) {
    let role = roles[i];
    let temp = {
      roleId: role.id,
      roleName: role.roleName,
      unitId: undefined,
      unitName: undefined,
      departRole: role.departRole
    };
    if (temp.departRole) {
      //部门角色
      if (isNotEmpty(real(departData).id)) {
        temp.unitId = real(departData).id;
        temp.unitName = real(departData).unitName;
        list.push(temp);
      }
    } else {
      //单位角色
      temp.unitId = real(unitData).id;
      temp.unitName = real(unitData).unitName;
      list.push(temp);
    }
  }
  userData.value.userRoles = list;
}

function loadUserData({id}) {
  loading.value = true;
  getAction('/sys/user/loadUserById', {id}).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      userData.value = result;
    }
  });
}

function loadUserPositionSort() {
  loading.value = true;
  getAction('/sys/user/loadUserPositionSort').then(data => {
    loading.value = false;
    if (data.success) {
      userData.value.userPositionSort = data.result;
    }
  });
}

function loadUnitPositionLevel() {
  let params = {
    current: 1,
    size: 1000
  };
  loading.value = true;
  params.unitId = unitData.id;
  getAction('/sys/positionLevel/loadUnitPositionLevel',
    params).then(data => {
    loading.value = false;
    if (data.success) {
      positionLevelOptions.value = data.result.records;
    }
  });
}

function loadUnitPositions() {
  loading.value = true;
  getAction('/sys/position/loadUnitPosition',
    {unitId: unitData.id, current: 1, size: 1000}).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      positionOptions.value = result.records;
    }
  });
}

function createDefaultValue() {
  let data = {
    userStatus: '0'
  };

  if (isNotEmpty(real(departData)) && isNotEmpty(real(departData).id)) {
    data.userPositionDepartId = real(departData).id;
  }
  return data;
}

const modalTitle = computed(() => {
  if (isEmpty(real(userData).id)) {
    return '新建用户';
  }
  return '编辑用户';
});

function ok() {
  refForm.value.validate((valid, errors) => {
    if (valid) {
      let userDataVo = real(real(userData));
      userDataVo.unitId = real(unitData).id;
      saveUser(userDataVo);
    }
  });
}

function saveUser(userDataVo) {
  loading.value = true;
  postAction('/sys/user/save', userDataVo).then(data => {
    loading.value = false;
    if (data.success) {
      ElMessage({
        message: '保存成功',
        type: 'success',
      });
      refFModal.value.close();
      emits('saved');
    }
  });
}

function loadUnitsByPath() {
  loading.value = true;
  getAction('/sys/unit/loadDepatrsByPath',
    {path: unitData.path}).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      setUnitTrees(result);
    }
  });
}

function setUnitTrees(list) {
  if (isEmpty(list)) list = [];
  list.forEach(item => {
    if (item.type + '' === '0') {
      item.disabled = true;
    }
  });
  departTrees.value = listToTrees(list);
}

defineExpose({
  setData
});
</script>
<script>
export default {
  name: 'UserEditModal'
};
</script>
<style>
.user-edit-body {
  height: 100%;
  width: 100%;
  display: flex;
}

.user-edit-left,
.user-edit-right {
  height: 100%;
  flex: 0.5;
  padding: 0 30px;
}
</style>
